package com.springboot.news.controller;

import com.springboot.news.domain.dto.FruitDTO;
import com.springboot.news.domain.po.Fruit;
import com.springboot.news.domain.po.Result;
import com.springboot.news.domain.query.FruitQuery;
import com.springboot.news.domain.vo.FruitVO;
import com.springboot.news.domain.vo.PageableVO;
import com.springboot.news.service.FruitService;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/fruit")
public class FruitController {
//    vo是返回给前端展示，dto是springboot使用的类
    @Resource
    private FruitService fruitService;

    @GetMapping("/tableList")
    public Result<PageableVO<FruitVO>> tableList(FruitQuery dto) {
        return Result.success(fruitService.tableList(dto));
    }
    @GetMapping("/list")
    public Result<List<FruitVO>> list(@RequestParam(required = false) String fruitName ) {
        List<Fruit> list = fruitService.list(fruitName);
        List<FruitVO> voList = new ArrayList<>();
        for(Object item: list) {
            FruitVO vo = new FruitVO();
            BeanUtils.copyProperties(item, vo);
            voList.add(vo);
        }
        return Result.success(voList);
    }
    @PostMapping("/addList")
    public Result<String> addList(@RequestBody @Validated(FruitDTO.Add.class) FruitDTO dto) {
        fruitService.addList(dto);
        return Result.success("添加成功");
    }
    @DeleteMapping("/delete")
    public Result<String> delete(@RequestParam Integer id) {
        fruitService.delete(id);
        return Result.success("删除成功");
    }
    @PostMapping("/update")
    public Result<String> updateTable(@RequestBody @Validated(FruitDTO.Update.class) FruitDTO dto) {
        fruitService.updateTable(dto);
        return Result.success("更新成功");
    }
    @GetMapping("FruitDetail")
    public Result<FruitVO> fruitDetail(@RequestParam Integer id) {
        return Result.success(fruitService.fruitDetail(id));
    }

}
